//route包函数封装
//route.go
package route

import (
	"fmt"
	"log"
	"net/http"
)

type MyMux struct {
	handlers map[string][]*Handler //用于存储http.HandleFunc("/", SayhelloName) 格式的路由规则
}

type Handler struct {
	path string
	http.HandlerFunc
}

//开启http服务
func (m *MyMux) Listen(port string) {
	err := http.ListenAndServe(port, m)
	if err != nil {
		log.Fatal("开启http服务错误!")
	}
}

func NewMyMux() *MyMux {
	return &MyMux{make(map[string][]*Handler)}
}

func (p *MyMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	//下面是路由处理，一般web框架会使用一个封装函数统一处理
	if r.URL.Path == "/" {
		sayhelloName(w, r) //这是所有web框架路由的核心代码
		return
	}
	http.NotFound(w, r)
	return
}

func sayhelloName(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(w, "Hello MyMuxRoute!")
}
